package com.wshl.aijiuunion.utils;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;

import com.baidu.location.BDLocation;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.wshl.aijiuunion.GlobConstant;


import java.util.List;

public class LocationUtil {


    public static final int GPS_REQUEST_CODE = 10;


    /**
     * 判断定位服务是否开启
     *
     * @param
     * @return true 表示开启
     */
    public static boolean isLocationEnabled(Context context) {
        int locationMode = 0;
        String locationProviders;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
                return false;
            }
            return locationMode != Settings.Secure.LOCATION_MODE_OFF;
        } else {
            locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }
    }

    //打开定位服务
    private static void openLocationService(Activity context) {
        Intent intent = new Intent();
        //定位服务页面
        intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            //startActivity(intent);
            context.startActivityForResult(intent, GPS_REQUEST_CODE);
        } catch (ActivityNotFoundException ex) {
            //如果页面无法打开，进入设置页面
            intent.setAction(Settings.ACTION_SETTINGS);
            try {
                context.startActivityForResult(intent, GPS_REQUEST_CODE);
                //startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 跳转GPS设置
     */
    public static void openGPSSettings(final Activity context) {
        isShouldGetLocation = false;
        if (isLocationEnabled(context)) {
            getLocation(context);
        } else {

            DialogUtil.showNormaldialog(context, "请打开位置服务", false, false);
            DialogUtil.setOndialgConfirm(new DialogUtil.OnDialogConfirm() {
                @Override
                public void setConfirm() {
                    SPUtils.getInstance().put(GlobConstant.OPENLOCATION,true);
                    openLocationService(context);
                }

                @Override
                public void setCancel() {
                    //如果用户拒绝打开位置服务
                    context.finish();
                    AppUtils.exitApp();
                }

                @Override
                public void getInput(String input) {

                }
            });
        }
    }

    public static boolean isShouldGetLocation = true;//是否需要检测定位

    //获取经纬度
    public static void getLocation(final Activity context) {
        XXPermissions.with(context)
                .constantRequest() //设置被拒绝后继续申请，直到用户授权或者永久拒绝
                // .permission(Permission.SYSTEM_ALERT_WINDOW, Permission.REQUEST_INSTALL_PACKAGES) //支持请求6.0悬浮窗权限8.0请求安装权限
                .permission(Permission.Group.LOCATION, Permission.Group.STORAGE) //不指定权限则自动获取清单中的危险权限
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        BdLocationUtil.getInstance().requestLocation(new BdLocationUtil.MyLocationListener() {
                            @Override
                            public void myLocation(BDLocation location) {
                                if (location != null) {

                                    //  LogUtils.e(location.getAddress().address + "," + location.getLatitude() + "," + location.getLongitude());
                                    //ToastUtils.showLong(location.getAddress().address + "," + location.getLatitude() + "," + location.getLongitude());
                                    if (mListener != null) {
                                        mListener.getLocationInfo(location.getLongitude(), location.getLatitude());
                                        mListener.getLocation(location.getLongitude(), location.getLatitude(), location.getProvince(), location.getCity(), location.getDistrict());
                                    }


                                } else {
                                    ToastUtils.showLong("定位失败,请稍后重试");
                                }
                            }
                        });

                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        //如果权限被永久禁止,quick值为true
                        //让用户手动打开权限设置
                        if (quick) {
                            DialogUtil.showNormaldialog(context, "请打开定位权限", false, true);
                            DialogUtil.setOndialgConfirm(new DialogUtil.OnDialogConfirm() {
                                @Override
                                public void setConfirm() {
                                    isShouldGetLocation = true;
                                    XXPermissions.gotoPermissionSettings(context);
                                }

                                @Override
                                public void setCancel() {
                                    context.finish();

                                }

                                @Override
                                public void getInput(String input) {

                                }
                            });

                        }

                    }
                });
    }

    public static GetLocationListener mListener;

    public static void setOnGetLocationListener(GetLocationListener getLocationListener) {
        mListener = getLocationListener;

    }

    public interface GetLocationListener {

        void getLocationInfo(double longtitude, double latitude);

        void getLocation(double longtitude, double latitude, String province, String city, String country);
    }


    /**
     * 坐标转换，百度地图坐标转换成腾讯地图坐标
     *
     * @param lat 百度坐标纬度
     * @param lon 百度坐标经度
     * @return 返回结果：纬度,经度
     */
    public static String map_bd2tx(double lat, double lon) {
        double tx_lat;
        double tx_lon;
        double x_pi = 3.14159265358979324;
        double x = lon - 0.0065, y = lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
        tx_lon = z * Math.cos(theta);
        tx_lat = z * Math.sin(theta);
        return tx_lat + "," + tx_lon;
    }

    /**
     * 坐标转换，腾讯地图转换成百度地图坐标
     *
     * @param lat 腾讯纬度
     * @param lon 腾讯经度
     * @return 返回结果：经度,纬度
     */
    public static String map_tx2bd(double lat, double lon) {
        double bd_lat;
        double bd_lon;
        double x_pi = 3.14159265358979324;
        double x = lon, y = lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        bd_lon = z * Math.cos(theta) + 0.0065;
        bd_lat = z * Math.sin(theta) + 0.006;

        System.out.println("bd_lat:" + bd_lat);
        System.out.println("bd_lon:" + bd_lon);
        return bd_lon + "," + bd_lat;
    }


}
